import * as monaco from 'monaco-editor'
import { HighLightOptions } from './high-light.js'
import CompletionItemProvider from './completion.js'
import FoldingRangeProvider from './folding.js'
import SignatureHelpProvider from './signature.js'
import HoverProvider from './hover.js'

// 跟踪语言是否已初始化
let isLanguageInitialized = false

export const initializeMagicScript = () => {
  // 如果已经初始化，直接返回
  if (isLanguageInitialized) {
    console.log('MagicScript 语言已经初始化过，跳过重复初始化')
    return
  }

  console.log('开始初始化 MagicScript 语言')
  const language = 'magicscript'

  // 检查是否已注册语言
  const isLanguageRegistered = monaco.languages.getLanguages().some((lang) => lang.id === language)
  console.log('语言是否已注册:', isLanguageRegistered)

  if (!isLanguageRegistered) {
    // 注册语言
    monaco.languages.register({ id: language })
    // 设置语言选项
    monaco.languages.setLanguageConfiguration(language, {
      wordPattern: /(-?\d*\.\d\w*)|([^`~!#%^&*()\-=+[{\]}\\|;:'",.<>/?\s]+)/g,
      brackets: [
        ['{', '}'],
        ['[', ']'],
        ['(', ')']
      ],
      comments: {
        lineComment: '//',
        blockComment: ['/*', '*/']
      },
      operators: [
        '<=',
        '>=',
        '==',
        '!=',
        '+',
        '-',
        '*',
        '/',
        '%',
        '&',
        '|',
        '!',
        '&&',
        '||',
        '?',
        ':',
        '++',
        '--',
        '+=',
        '-=',
        '*=',
        '/='
      ],
      autoClosingPairs: [
        { open: '{', close: '}' },
        { open: '[', close: ']' },
        { open: '(', close: ')' },
        { open: '"""', close: '"""', notIn: ['string.multi'] },
        { open: '"', close: '"', notIn: ['string'] },
        { open: "'", close: "'", notIn: ['string'] }
      ]
    })

    // 设置高亮
    monaco.languages.setMonarchTokensProvider(language, HighLightOptions)

    // 设置折叠
    monaco.languages.registerFoldingRangeProvider(language, FoldingRangeProvider)
    // 设置参数提示
    monaco.languages.registerSignatureHelpProvider(language, SignatureHelpProvider)
    // 设置悬浮提示
    monaco.languages.registerHoverProvider(language, HoverProvider)

    // 设置代码提示
    monaco.languages.registerCompletionItemProvider(language, CompletionItemProvider)
    console.log('代码提示提供者已注册')

    // 注册完成后再次确认
    console.log(
      '语言注册后再次检查:',
      monaco.languages.getLanguages().some((lang) => lang.id === language)
    )

    // 标记为已初始化
    isLanguageInitialized = true
  } else {
    // 如果语言已注册但尚未标记为初始化，现在标记
    isLanguageInitialized = true
    console.log('MagicScript 语言已存在，标记为已初始化')
  }
}
